import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_app/utils/PackageInfoUtils.dart';
import 'package:flutter_app/utils/channel/CommonChannel.dart';
import 'package:flutter_app/utils/open_file_utils.dart';
import 'package:flutter_app/utils/path_provider_utils.dart';
import 'package:flutter_app/utils/url_launcher_utils.dart';

import 'app_market.dart';
import 'app_upgrade.dart';

/**
 * @Description: java类作用描述
 * @Author: 下雨了
 * @CreateDate: 2022-01-06 15:44
 * @UpdateUser: 更新者
 * @UpdateDate:  2022-01-06 15:44
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
///
const String FLUTTER_APP_UPGRADE = "flutter_app_upgrade";

class FlutterUpgrade {
  static const MethodChannel _channel = MethodChannel(FLUTTER_APP_UPGRADE);

  ///
  /// 获取app信息
  ///
  static Future<AppInfo> get appInfo async {
    return AppInfo(
        versionName: await PackageInfoUtils().getVersion(),
        versionCode: await PackageInfoUtils().getBuildNumber(),
        packageName: await PackageInfoUtils().getPackageName());
  }

  ///
  /// 获取apk下载路径
  ///
  static Future<String> get apkDownloadPath async {
    return await PathProviderUtils().getExtPath();
  }

  ///
  /// Android 安装app
  ///
  static installAppForAndroid(String path) async {

    CommonChannel.getInstance()?.installApk(path);
    // OpenResult openResult =  await OpenFileUtils().open(path, type: "application/vnd.android.package-archive");
    // print(openResult.message);
    // print(openResult.type.toString());
  }

  ///
  /// 跳转到ios app store
  ///
  static toAppStore(String id) async {
    String url = "https://apps.apple.com/cn/app/apple-store/id$id";
    await UrlLauncherUtils().launchs(url);
  }

  ///
  /// 获取android手机上安装的应用商店
  ///
  static getInstallMarket({List<String>? marketPackageNames}) async {
    List<String> packageNameList = AppMarket.buildInPackageNameList;
    if (marketPackageNames != null && marketPackageNames.isNotEmpty) {
      packageNameList.addAll(marketPackageNames);
    }
    var map = {'packages': packageNameList};
    var result = await _channel.invokeMethod('getInstallMarket', map);
    List<String> resultList = (result as List).map((f) {
      return '$f';
    }).toList();
    return resultList;
  }

  ///
  /// 跳转到应用商店
  ///
  static toMarket({required AppMarketInfo appMarketInfo}) async {
    var map = {
      'marketPackageName': appMarketInfo != null ? appMarketInfo.packageName : '',
      'marketClassName': appMarketInfo != null ? appMarketInfo.className : ''
    };
    return await _channel.invokeMethod('toMarket', map);
  }
}